package pl.edu.pk.mech.kkbus.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.springframework.stereotype.Service;
import pl.edu.pk.mech.kkbus.component.MyEntityManagerFactory;
import pl.edu.pk.mech.kkbus.entities.Refueling;

@Service
public class RefuelingService {

    EntityManagerFactory emf = MyEntityManagerFactory.get();
    
    public boolean create(pl.edu.pk.mech.kkbus.dto.Refueling r) {
        EntityManager em = null;        
        try {
            em = emf.createEntityManager();
            Refueling refueling = new Refueling(r.getLiters(), r.getCosts(),
                    r.getDate(), r.getBusId());
            em.persist(refueling);
            
            return true;
        } catch(Exception e) {
            return false;
        } finally {
            if (em != null)
                em.close();
        }
    }
    
    public boolean update(long id, pl.edu.pk.mech.kkbus.dto.Refueling r) {
        EntityManager em = null;        
        try {
            em = emf.createEntityManager();
            Refueling refueling = em.find(Refueling.class, new Long(id));
            refueling.setBusId(r.getBusId());
            refueling.setCosts(r.getCosts());
            refueling.setDate(r.getDate());
            refueling.setLiters(r.getLiters());
            
            em.persist(refueling);
            
            return true;
        } catch(Exception e) {
            return false;
        } finally {
            if (em != null)
                em.close();
        }
    }
    
    public boolean delete(long id) {
        EntityManager em = null;        
        try {
            em = emf.createEntityManager();
            Refueling refueling = em.find(Refueling.class, new Long(id));        
            em.remove(refueling);
            
            return true;
        } catch(Exception e) {
            return false;
        } finally {
            if (em != null)
                em.close();
        }
    }         
}
